package com.cma.typhoon.web.controller;

import com.cma.model.db.LogInfo;
import com.cma.model.param.HistctrackParam;
import com.cma.model.param.Lonlat;
import com.cma.model.resultdb.SimpleTf;
import com.cma.service.HistctrackService;
import com.cma.service.LogInfoService;
import com.cma.service.TcrealtimeService;
import com.cma.util.DateUtils;
import com.cma.util.MapUtil;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.geom.Point2D;
import java.util.*;

/**
 * @Author hbb
 * @Date 2016/12/31 16:48
 */
@Controller

@RequestMapping("/tf")
public class HistctrackController {
    @Autowired
    private HistctrackService histctrackService;
    @Autowired
    private TcrealtimeService tcrealtimeService;
    @Autowired
    private LogInfoService logInfoService;

    /**
     * 综合查询
     *
     * @param model
     * @param histctrackParam
     * @return
     */
    @RequestMapping("/main")
    @ResponseBody
    public Object index(Model model, HistctrackParam histctrackParam) {
        // TODO 查询日志记录

        Subject sub = SecurityUtils.getSubject();
        String userName = (String) sub.getPrincipal();
        if (!StringUtils.isEmpty(userName)) {
            LogInfo logInfo = new LogInfo();
            logInfo.setUserName(userName);
            logInfo.setFtype("查询");
            JSONObject object = JSONObject.fromObject(histctrackParam);
            logInfo.setFdesc("参数:" + object.toString());
            logInfo.setCreateTime(new Date());
            logInfoService.save(logInfo);
        }
        // TODO 先查看是否有多边形，如果有多边形则先处理多边形内容
        histctrackParam = handleParm(histctrackParam);

        // TODO 台风风速统计
//        Map<String, String> map = tcrealtimeService.getMaxFs(histctrackParam);
//        Map<String, String> map2 = histctrackService.getMaxFs(histctrackParam);
//        //结合一下 如果遍历实时库里面的统计 如果实时库里面有历史库中不存在的统计则添加进去
//        for (Map.Entry<String, String> entry : map.entrySet()) {
//            if (!map2.containsKey(entry.getKey())) {
//                map2.put(entry.getKey(), entry.getValue());
//            }
//        }
        // TODO 台风数据
        List<SimpleTf> list = histctrackService.queryTfByParams(histctrackParam);

        List<SimpleTf> restlist = histctrackService.queryMaxWind(list);
        StringBuffer tfbhsStr = new StringBuffer();
        for (SimpleTf tf:restlist){
            tfbhsStr.append(",");
            tfbhsStr.append("'"+tf.getTfbh()+"'");
        }
        // TODO 台风强度频次
        Map<String, String> map3 = tcrealtimeService.getStrengthStat(tfbhsStr.toString().substring(1));//从实时库中获取强度频次统计
        Map<String, String> map4 = histctrackService.getStrengthStat(tfbhsStr.toString().substring(1));//从历史库中获取强度频次统计

        String[] tyArray = {"TC", "TD", "TS", "STS", "TY", "STY", "SuperTY"};
        Map mapTc = new LinkedHashMap<>();
        for (int i = 0; i < tyArray.length; i++) {
            String type = tyArray[i];
            int tc = (map3.containsKey(type) ? Integer.valueOf(map3.get(type)) : 0) + (map4.containsKey(type) ? Integer.valueOf(map4.get(type)) : 0);
            mapTc.put(type, tc);
        }
//        String year = DateUtils.getYear();
//        Map mapFs = new LinkedHashMap<>();
//        int years = Integer.valueOf(year);
//        for (int i = years; i > (years - 7); i--) {
//            mapFs.put(i, map2.get(i + "") == null ? 0 : map2.get(i + ""));
//        }


        Map maps = new HashMap<>();
//        maps.put("maxFs", mapFs);
        maps.put("strength", mapTc);
        maps.put("data", restlist);
        return maps;
    }


    private HistctrackParam handleParm(HistctrackParam histctrackParam) {
        //   histctrackParam.setLonlatList("140.1,7.7;138.9,12.3;137.6,13.2;137.4,13.4");
        List<Lonlat> listall = new ArrayList<Lonlat>();
        // TODO 最终的结果
        //List<Lonlat> listResult=new ArrayList<>();
        // TODO 台风编号结果
        String tfbhs = histctrackParam.getTfbhs();
        if (!StringUtils.isEmpty(histctrackParam.getLonlatList())) {
            // TODO 先解析字符串
            String lonlatList = histctrackParam.getLonlatList().replaceAll("\\),\\(",";").replaceAll("[\\(\\)]","");
            String[] lonlat = lonlatList.split(";");
            List<Lonlat> list = new ArrayList<>();


            // List<String> tfbhs=new ArrayList<String>();
            // TODO 先解析出来数据
            // TODO 筛选出来最大，最小的经纬度
            Lonlat maxLonlat = new Lonlat();
            Lonlat minLonlat = new Lonlat();
            if (lonlat.length > 0) {
                String maxLon = lonlat[0].split(",")[1],
                        maxLat = lonlat[0].split(",")[0],
                        minlon = lonlat[0].split(",")[1],
                        minlat = lonlat[0].split(",")[0];
                for (int i = 0; i < lonlat.length; i++) {
                    if(!StringUtils.isEmpty(lonlat[i])) {
                        String lon = lonlat[i].split(",")[1];
                        String lat = lonlat[i].split(",")[0];
                        if (Float.valueOf(lon) >= Float.valueOf(maxLon)) {
                            maxLon = lon;
                        }
                        if (Float.valueOf(lon) <= Float.valueOf(minlon)) {
                            minlon = lon;
                        }
                        if (Float.valueOf(lat) >= Float.valueOf(maxLat)) {
                            maxLat = lat;
                        }
                        if (Float.valueOf(lat) <= Float.valueOf(minlat)) {
                            minlat = lat;
                        }
                        Lonlat ll = new Lonlat();
                        ll.setLon(lonlat[i].split(",")[1]);
                        ll.setLat(lonlat[i].split(",")[0]);
                        list.add(ll);
                    }
                }
                // TODO 将筛选出来的数据组装一下
                maxLonlat.setLat(maxLat);
                maxLonlat.setLon(maxLon);
                minLonlat.setLon(minlon);
                minLonlat.setLat(minlat);
                // TODO 调取方法利用最大最小经纬点组成矩形筛选出来一组数据
                List<Lonlat> listNew = tcrealtimeService.findDataByRect(maxLonlat, minLonlat);
                List<Lonlat> listOld = histctrackService.findDataByRect(maxLonlat, minLonlat);
                listall.addAll(listNew);
                listall.addAll(listOld);
            }
            // TODO 将范围参数转换为点的集合
            List<Point2D.Double> pts = new ArrayList<>();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    pts.add(new Point2D.Double(Double.valueOf(list.get(i).getLon()), Double.valueOf(list.get(i).getLat())));
                }
            }
            // TODO 转换为点的集合后 进行筛选处理，调用MapUtil.IsPtInPoly（） 方法来判断改点是否是在所述范围内
            try {
                if (listall != null && listall.size() > 0) {
                    for (int i = 0; i < listall.size(); i++) {
                        Lonlat ll = listall.get(i);
                        String tfbh = ll.getTfbh();

                        if (!tfbhs.contains(tfbh)) {
                            Point2D.Double po = new Point2D.Double(Double.valueOf(listall.get(i).getLon()), Double.valueOf(listall.get(i).getLat()));
                            if (MapUtil.IsPtInPoly(po, pts)) {
                                if (tfbhs.length() > 0) {
                                    tfbhs = tfbhs + ";" +"'"+ listall.get(i).getTfbh()+"'";
                                } else {
                                    tfbhs ="'"+ listall.get(i).getTfbh()+"'";
                                }
                                // tfbhs.add(listall.get(i).getTfbh());
                                // listResult.add(listall.get(i));
                            }
                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        histctrackParam.setTfbhs(tfbhs);
        return histctrackParam;
    }

    /**
     * 根据台风编号与台风名称（英文）获取对应的台风信息
     *
     * @param model
     * @param histctrackParam
     * @return
     */
    @RequestMapping("/tfsource")
    @ResponseBody
    public Object tfsource(Model model, HistctrackParam histctrackParam) {
   /*     histctrackParam.setXuhao("20060001");
        histctrackParam.setTfname("CHANCHU");
        histctrackParam.setTy("new");*/
        return histctrackService.findTfInfo(histctrackParam);
    }


}
